package com.ctrip.demo.leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

public class LeetCode515 {

    public static void main(String[] args) {

        TreeNode root = new TreeNode(1, new TreeNode(3, new TreeNode(5), new TreeNode(3)), new TreeNode(2, null, new TreeNode(9)));
        List<Integer> list = largeValues(root);

        list.stream().forEach(System.out::println);

    }

    static List<Integer> integers = new ArrayList<>();
    public static List<Integer> largeValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();
//        dfs(root, res, 0);
//
//        integers.stream().forEach(System.out::print); System.out.println();
//        System.out.println("===========================");
        checkFun02(root, res);

        return res;
    }

    public static void checkFun02(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int len = queue.size();
            // 第一个节点值
            int max = queue.getFirst().val;
            for (int i = 0; i < len; i++) {
                TreeNode treeNode = queue.removeFirst();
                if (treeNode.val > max) {
                    max = treeNode.val;
                }
                if (treeNode.left != null) {
                    queue.add(treeNode.left);
                }

                if (treeNode.right != null) {
                    queue.add(treeNode.right);
                }
            }
            res.add(max);
        }
    }

    private static void dfs(TreeNode root, List<Integer> res, int level) {
        if (root == null) {
            return;
        }
        if (!integers.contains(level)) {
            integers.add(level);
        }
        if (level >= res.size()) {
            res.add(level, root.val);
        } else {
            Integer val = res.get(level);
            if (root.val > val) {
                res.set(level, root.val);
            }
        }

        dfs(root.left, res, level + 1);
        dfs(root.right, res, level + 1);
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}